package com.zrc.ke.core;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ProxyReceiver extends BroadcastReceiver {

    private String receiverName;

    public ProxyReceiver(String name) {
        this.receiverName = name;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Class receiverClass = PluginManager.getInstance(context).getDexClassLoader().loadClass(receiverName);
            Object receive = receiverClass.newInstance();
//            BaseReceiver baseReceiver = (BaseReceiver) receive;
//            baseReceiver.onReceive(context, intent);
            invokeMethod(receiverClass,receive,true,"onReceive", new Class[]{Context.class,Intent.class}, new Object[]{context,intent});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void invokeMethod(Class localClass, Object activity, Boolean isPublic, String methodName, Class[] parmsClass, Object[] parms) {
        try {
            Method method;
            if (isPublic) {
                method = localClass.getMethod(methodName, parmsClass);
            } else {
                method = localClass.getDeclaredMethod(methodName, parmsClass);
            }
            method.setAccessible(true);
            if (method != null) {
                method.invoke(activity, parms);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
